<template>
  <PublicLoading v-if="loading.mounted" />
  <div v-else class="dt-main-tabs-content">
    <!-- <div class="dt-content-left">
      <PmChatList />
    </div> --><!--可选-->
    <div class="dt-content-main">
      <div class="dt-content-head">
        <div class="dt-content-head-tab">
          <div class="dt-head-title">
            <!-- <div class="dt-head-breadcrumb" @click.stop="goBack">
              <i class="el-icon-arrow-left"></i>
              <span>返回</span>
              <em>|</em>
            </div> -->
            <span>创建项目</span>
          </div>
        </div>
      </div>
      <div class="dt-content-page">
        <el-form :model="createPmRuleForm" :rules="createPmRules" ref="createPmRuleForm" label-width="118px" label-position="left"
          class="dt-create-pm-box">
          <el-form-item label="项目名称" prop="projectName" class="dt-project-name">
            <el-input type="text" placeholder="请输入项目名称" v-model.trim="createPmRuleForm.projectName" maxlength="40" show-word-limit style="width:800px"
              @blur="saveFormData">
            </el-input>
          </el-form-item>
          <el-form-item label="项目产值" prop="output" class="dt-je-box por">
            <el-input placeholder="请输入项目产值" v-model.trim="createPmRuleForm.output" style="width:540px" @input="outputInput" @blur="saveFormData">
              <template slot="append">元</template>
            </el-input>
            <div v-if="createPmRuleForm.output!=0" class="dt-je-china poa">{{$tools.moneyLower(createPmRuleForm.output)}}</div>
          </el-form-item>
          <el-form-item label="计划工期" prop="planDays">
            <el-input placeholder="天数" v-model.trim="createPmRuleForm.planDays" maxlength="6" style="width:120px" @input="planDaysInput"
              @blur="planDaysBlur">
              <template slot="append">天</template>
            </el-input>
            <el-date-picker v-model="createPmRuleForm.dateArr" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
              style="width:407px; margin-left:10px;" @change="dateArrBlur" :clearable="false" @blur="saveFormData">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="项目负责人" prop="projectMaster">
            <!--团队成员、外部成员-->
            <PublicSelectCompanyUser :option="optProjectMaster" @select="selectUser($event,'projectMaster')" ref="ProjectMasterSelectUser"
              @blur="saveFormData" />
          </el-form-item>
          <el-form-item label="项目概述" prop="description">
            <el-input type="textarea" placeholder="请描述项目基本情况" v-model="createPmRuleForm.description" maxlength="2000" rows="9" show-word-limit
              @focus="focusTextarea(0)" @blur="blurTextarea(0)" :class="{'is-focus':textareaFocus[0]}">
            </el-input>
          </el-form-item>
          <el-form-item label="工作内容" prop="workContent">
            <el-input type="textarea" placeholder="请描述项目工作主要内容和涉及专业" v-model="createPmRuleForm.workContent" maxlength="2000" rows="9" show-word-limit
              @focus="focusTextarea(1)" @blur="blurTextarea(1)" :class="{'is-focus':textareaFocus[1]}">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitFormCreatePm('createPmRuleForm')" :loading="loading.createPmLoading">设置项目组织架构</el-button>
            <el-button @click="resetFormCreatePm('createPmRuleForm')" style="width:154px;">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

  </div>
</template>
<script>
export default {
  data() {
    return {
      uid: this.$tools.getDecrypt(this.$store.state.uid), //用户id
      loading: {
        mounted: false,
        createPmLoading: false
      },
      createPmRuleForm: {
        projectName: '',
        output: '',
        planDays: '',
        dateArr: [],
        projectMaster: '',
        description: '',
        workContent: ''
      },
      createPmRules: {
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' },
          { min: 5, max: 40, message: '请输入5-40字项目名称', trigger: 'blur' }
        ],
        output: [
          { required: true, message: '请输入项目产值', trigger: 'blur' },
          { validator: this.validateOutput, trigger: 'blur' }
        ],
        planDays: [
          { required: true, message: '请输入计划工期', trigger: 'blur' },
          { validator: this.validateDay, trigger: 'blur' }
        ]
      },
      //日期配置/不可选范围
      pickerOptions: {
        disabledDate: (date) => {
          return date < new Date().getTime() - 3600 * 1000 * 24
        }
      },
      //专业-负责人的选人配置
      optProjectMaster: {
        width: '540px',
        placeholder: '请选择负责人，最多设置3人',
        isMultiple: true, //是否多选
        maxSelect: 3, //单选忽略
        //已选的成员列表
        selectedUserList: [],
        //团队成员列表
        companyUserList: []
      },
      textareaFocus: [false, false]
    }
  },
  computed: {
    query() {
      return this.$tools.getQuery(this)
    }
  },
  methods: {
    goBack() {
      this.$router.push('/main/#/pm?tab=list&elTab=0')
    },
    outputInput(value) {
      if (this.createPmRuleForm.output.indexOf('.') < 0) {
        this.createPmRuleForm.output = this.createPmRuleForm.output.split('.')[0].substring(0, 9)
      } else if (this.createPmRuleForm.output.split('.')[0].length > 9) {
        this.createPmRuleForm.output =
          this.createPmRuleForm.output.split('.')[0].substring(0, 9) +
          (this.createPmRuleForm.output.split('.')[1] ? '.' + this.createPmRuleForm.output.split('.')[1] : '')
      }
      let that = this
      let regStrs = [
        ['^0(\\d+)$', '$1'],
        ['[^\\d\\.]+$', ''],
        ['\\.(\\d?)\\.+', '.$1'],
        ['^(\\d+\\.\\d{2}).+', '$1']
      ]
      for (let i = 0; i < regStrs.length; i++) {
        let reg = new RegExp(regStrs[i][0])
        that.createPmRuleForm.output = that.createPmRuleForm.output.replace(reg, regStrs[i][1])
        // console.log(value.replace(reg, regStrs[i][1]), i)
      }
    },
    planDaysInput(value) {
      // 只允许输入数字
      this.createPmRuleForm.planDays = value.replace(/[^\d]/g, '')
    },
    planDaysBlur() {
      if (this.createPmRuleForm.planDays > 0) {
        const today = new Date()
        const date = new Date()
        let planDays = this.createPmRuleForm.planDays || 0
        date.setTime(date.getTime() + 3600 * 1000 * 24 * (planDays - 1))
        this.createPmRuleForm.dateArr = [today, date]
      }
      this.saveFormData()
    },
    dateArrBlur() {
      // console.log(this.createPmRuleForm.dateArr, 888)
      if (this.createPmRuleForm.dateArr && this.createPmRuleForm.dateArr[0]) {
        let startTime = this.createPmRuleForm.dateArr[0].getTime()
        let endTime = this.createPmRuleForm.dateArr[1].getTime()
        let planDays = (endTime - startTime) / (3600 * 1000 * 24)
        this.createPmRuleForm.planDays = planDays + 1
      }
    },
    validateOutput(rule, value, callback) {
      var reg = /^(([1-9]\d{0,8}(\.\d{1,2})?)|(0\.\d{1,2}))$/
      if (!reg.test(this.createPmRuleForm.output)) {
        callback(new Error('请输入正确的产值'))
      } else {
        callback()
      }
    },
    validateDay(rule, value, callback) {
      if (value <= 0) {
        callback(new Error('请输入大于0工期天数'))
      } else {
        callback()
      }
    },
    //管理单位、合作单位、专业选人后回调
    selectUser(ids, type) {
      console.log(ids, type)
      switch (type) {
        case 'projectMaster':
          this.createPmRuleForm.projectMaster = ids
          break
      }
    },
    createProject() {
      var data = [
          {
            userId: this.uid,
            projectName: this.createPmRuleForm.projectName,
            output: this.createPmRuleForm.output,
            planDays: this.createPmRuleForm.planDays,
            startTime: this.$tools.getDateFormatString('ymdhms', this.createPmRuleForm.dateArr[0]).substring(0, 10) + ' 00:00:00',
            endTime: this.$tools.getDateFormatString('ymdhms', this.createPmRuleForm.dateArr[1]).substring(0, 10) + ' 23:59:59',
            projectMaster: this.createPmRuleForm.projectMaster,
            description: this.createPmRuleForm.description,
            workContent: this.createPmRuleForm.workContent
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/project/createProject'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.$message({
                message: data.message,
                type: 'success',
                duration: '2000',
                onClose: () => {
                  //设置项目名称 给标签用
                  this.setStoreProjectName(data.data.id, data.data.projectName)
                  this.$cookies.set('projectName', this.getStoreProjectName(), { path: '/', maxAge: 60 * 60 * 24 })

                  this.loading.createPmLoading = false
                  localStorage.removeItem('createPmRuleForm')
                  this.createPmRuleForm = {
                    projectName: '',
                    output: '',
                    planDays: '',
                    dateArr: '',
                    projectMaster: '',
                    description: '',
                    workContent: ''
                  }
                  this.$router.push('/main/#/pm?tab=create&elTab=1&rootProjectId=' + data.data.id)
                }
              })
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                onClose: () => {
                  this.loading.createPmLoading = false
                }
              })
            }
          })
        })
        .catch((error) => {})
    },
    editProject() {
      var data = [
          {
            userId: this.uid,
            rootProjectId: this.query.rootProjectId,
            projectName: this.createPmRuleForm.projectName,
            output: this.createPmRuleForm.output,
            planDays: this.createPmRuleForm.planDays,
            startTime: this.$tools.getDateFormatString('ymdhms', this.createPmRuleForm.dateArr[0]).substring(0, 10) + ' 00:00:00',
            endTime: this.$tools.getDateFormatString('ymdhms', this.createPmRuleForm.dateArr[1]).substring(0, 10) + ' 23:59:59',
            projectMaster: this.createPmRuleForm.projectMaster,
            description: this.createPmRuleForm.description,
            workContent: this.createPmRuleForm.workContent
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/project/editProject'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.$message({
                message: data.message,
                type: 'success',
                duration: '2000',
                onClose: () => {
                  //设置项目名称 给标签用
                  this.setStoreProjectName(data.data.id, data.data.projectName)
                  this.$cookies.set('projectName', this.getStoreProjectName(), { path: '/', maxAge: 60 * 60 * 24 })

                  this.loading.createPmLoading = false
                  localStorage.removeItem('createPmRuleForm')
                  this.createPmRuleForm = {
                    projectName: '',
                    output: '',
                    planDays: '',
                    dateArr: [],
                    projectMaster: '',
                    description: '',
                    workContent: ''
                  }
                  this.$router.push('/main/#/pm?tab=create&elTab=1&rootProjectId=' + this.query.rootProjectId)
                }
              })
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                onClose: () => {
                  this.loading.createPmLoading = false
                }
              })
            }
          })
        })
        .catch((error) => {})
    },
    submitFormCreatePm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading.createPmLoading = true
          if (this.query.rootProjectId) {
            this.editProject()
          } else {
            this.createProject()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetFormCreatePm(formName) {
      this.$refs[formName].resetFields()
      this.$router.push('/main/#/pm?tab=list&elTab=0')
    },
    getPmChargeList() {
      var data = [
          {
            userId: this.uid
            //  rootProjectId: this.query.rootProjectId || ''
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/project/companyUserList'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data

            if (data.code === 200) {
              this.optProjectMaster.companyUserList = data.data
              // setTimeout(() => {
              //   this.$refs.ProjectMasterSelectUser.resetSelectUser()
              // }, 100)
            } else {
              this.optProjectMaster.companyUserList = []
            }
          })
        })
        .catch((error) => {})
    },
    showCard() {
      this.dataCard.isShowCard = true
    },
    //获取store 项目名称
    getStoreProjectName() {
      return this.$store.state.projectName ? JSON.parse(this.$store.state.projectName) : {}
    },
    //设置store 项目名称
    setStoreProjectName(projectId, projectName) {
      var storeProjectName = this.getStoreProjectName()
      storeProjectName[projectId] = projectName
      this.$store.commit('setProjectName', JSON.stringify(storeProjectName))
    },
    getProjectDetail() {
      var data = [
          {
            userId: this.uid,
            rootProjectId: this.query.rootProjectId
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/project/projectDetail'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              //设置项目名称 给标签用
              this.setStoreProjectName(this.query.rootProjectId, data.data.projectName)
              this.$cookies.set('projectName', this.getStoreProjectName(), { path: '/', maxAge: 60 * 60 * 24 })

              this.createPmRuleForm.projectName = data.data.projectName
              this.createPmRuleForm.output = data.data.output + ''
              this.createPmRuleForm.planDays = data.data.totalDays
              this.createPmRuleForm.dateArr.splice(0, 0, new Date(data.data.startTime))
              this.createPmRuleForm.dateArr.splice(1, 0, new Date(data.data.endTime))
              // this.createPmRuleForm.projectMaster = data.data.projectMaster
              this.createPmRuleForm.description = data.data.description
              this.createPmRuleForm.workContent = data.data.workContent

              //编辑专业 已选负责人列表
              this.optProjectMaster.selectedUserList = data.data.masters.filter((item) => {
                return item.masterState === 1
              })
              this.createPmRuleForm.projectMaster = this.optProjectMaster.selectedUserList
                .map((item) => {
                  return item.userId
                })
                .join()
              // setTimeout(() => {
              //   this.$refs.ProjectMasterSelectUser.resetSelectUser()
              // }, 1000)
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    focusTextarea(index) {
      this.textareaFocus.splice(index, 1, true)
    },
    blurTextarea(index) {
      this.textareaFocus.splice(index, 1, false)
      this.saveFormData()
    },
    saveFormData() {
      localStorage.removeItem('createPmRuleForm')
      // 在这里保存表单数据，可以使用 localStorage 或者其他方式
      localStorage.setItem('createPmRuleForm', JSON.stringify(this.createPmRuleForm))
    }
  },
  mounted() {
    if (this.query.rootProjectId) {
      this.getProjectDetail()
    } else {
      if (localStorage.getItem('createPmRuleForm')) {
        this.createPmRuleForm = JSON.parse(localStorage.getItem('createPmRuleForm'))
      }
    }
    this.getPmChargeList()
  }
  // watch: {
  //   //路由hash变化 加载组件
  //   $route(to, from) {
  //     if (to.hash !== from.hash) {
  //       this.getTaskList(this.nodeId)
  //     }
  //   }
  // },
  // beforeDestroy() {
  //   this.saveFormData()
  // },
  // beforeRouteLeave(to, from, next) {
  //   // 在离开当前页面之前保存表单数据
  //   this.saveFormData()
  //   console.log('456')
  //   next()
  // }
}
</script>
<style scoped>
.dt-create-pm-box {
  padding: 30px;
  width: 918px;
}
.dt-create-pm-box >>> .el-input-group__append {
  padding: 0 12.5px;
  color: #606266;
}
.dt-create-pm-box >>> .el-input__inner {
  height: 36px;
  line-height: 36px;
}

.dt-create-pm-box >>> .el-form-item__label,
.dt-create-pm-box >>> .el-form-item__content {
  line-height: 36px;
}

.dt-create-pm-box >>> .el-textarea__inner {
  padding: 8px;
}
.dt-create-pm-box >>> .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::after {
  content: '*';
  color: #f56c6c;
  margin-left: 4px;
}
.dt-create-pm-box >>> .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
  content: '';
  color: #f56c6c;
  margin-right: 0px;
}
.dt-je-china {
  top: 0;
  right: 330px;
  color: #909399;
}
</style>